<?php
//=======================================
// !! GYSN RELEASE - DO NOT REMOVE  !!
// !! DeZend by: syairx             !!
// !! Debug by: syairx & str/GYSN   !!
// !! Nullify by: str/GYSN & syairx !!
// !! GYSN RELEASE - DO NOT REMOVE  !!
//=======================================

define( "BUILDDATE", "06 Aug 2007 08:45:26 PM" );
define( "SWIFTPRODUCT", "SupportSuite" );
define( "SWIFTVERSION", "3.11.01" );
define( "BUILDTYPE", "STABLE" );

define( "INSWIFT", 1 );
define( "SWIFT_API", 10 );
define( "SWIFT_STAFF", 20 );
define( "SWIFT_ADMIN", 30 );
define( "SWIFT_CLIENT", 40 );
define( "SWIFT_WINAPP", 50 );
define( "SWIFT_CLI", 60 );
define( "SWIFT_SETUP", 70 );
define( "SWIFT_VISITOR", 80 );
define( "SWIFT_CALLBACK", 90 );
define( "SWIFT_WAP", 100 );
define( "SWIFT_CRON", 110 );
define( "SWIFT_CHAT", 120 );
define( "SWIFT_MONITOR", 130 );
define( "SWIFT_SYNCML", 140 );
define( "SWIFT_ARCHIVE", 150 );
define( "SWIFT_PDA", 160 );
define( "SWIFT_RSS", 170 );
define( "SWIFT_SYNCWORKS", 180 );
define( "SWIFT_INSTAALERT", 190 );
define( "SWIFT_MOBILE", 200 );

define( "EVENT_API", SWIFT_API );
define( "EVENT_STAFF", SWIFT_STAFF );
define( "EVENT_ADMIN", SWIFT_ADMIN );
define( "EVENT_CLIENT", SWIFT_CLIENT );
define( "EVENT_WINAPP", SWIFT_WINAPP );
define( "EVENT_CLI", SWIFT_CLI );
define( "EVENT_CALLBACK", SWIFT_CALLBACK );
define( "EVENT_WAP", SWIFT_WAP );
define( "EVENT_CRON", SWIFT_CRON );
define( "EVENT_VISITOR", SWIFT_VISITOR );
define( "EVENT_MONITOR", SWIFT_MONITOR );
define( "EVENT_SYNCML", SWIFT_SYNCML );
define( "EVENT_ARCHIVE", SWIFT_ARCHIVE );
define( "EVENT_PDA", SWIFT_PDA );
define( "EVENT_RSS", SWIFT_RSS );
define( "EVENT_SYNCWORKS", SWIFT_SYNCWORKS );
define( "EVENT_INSTAALERT", SWIFT_INSTAALERT );
define( "EVENT_MOBILE", SWIFT_MOBILE );

define( "SESSION_API", SWIFT_API );
define( "SESSION_STAFF", SWIFT_STAFF );
define( "SESSION_ADMIN", SWIFT_ADMIN );
define( "SESSION_CLIENT", SWIFT_CLIENT );
define( "SESSION_WINAPP", SWIFT_WINAPP );
define( "SESSION_CLI", SWIFT_CLI );
define( "SESSION_VISITOR", SWIFT_VISITOR );
define( "SESSION_WAP", SWIFT_WAP );
define( "SESSION_CHAT", SWIFT_CHAT );
define( "SESSION_MONITOR", SWIFT_MONITOR );
define( "SESSION_SYNCML", SWIFT_SYNCML );
define( "SESSION_ARCHIVE", SWIFT_ARCHIVE );
define( "SESSION_PDA", SWIFT_PDA );
define( "SESSION_RSS", SWIFT_RSS );
define( "SESSION_SYNCWORKS", SWIFT_SYNCWORKS );
define( "SESSION_INSTAALERT", SWIFT_INSTAALERT );
define( "SESSION_MOBILE", SWIFT_MOBILE );

define( "DATENOW", time( ) - date( "Z" ) );
define( "SWIFT_CRLF", "\n" );
define( "TITLEPREFIX", SWIFTPRODUCT.": " );

define( "SWIFT_FATAL", E_USER_ERROR );
define( "SWIFT_ERROR", E_USER_WARNING );
define( "SWIFT_WARNING", E_USER_NOTICE );

define( "TEMPLATE_FILE", "F" );
define( "TEMPLATE_DB", "D" );

define( "UGROUP_DEPARTMENT", 1 );
define( "UGROUP_TROUBLESHOOTER", 2 );
define( "UGROUP_DOWNLOADS", 3 );
define( "UGROUP_CFGROUP", 4 );
define( "UGROUP_PRIORITY", 5 );
define( "UGROUP_KNOWLEDGEBASE", 6 );
define( "UGROUP_NEWS", 7 );

define( "TGROUP_DEPARTMENT", 1 );
define( "TGROUP_TROUBLESHOOTER", 2 );
define( "TGROUP_DOWNLOADS", 3 );
define( "TGROUP_PRIORITY", 4 );
define( "TGROUP_KNOWLEDGEBASE", 5 );

define( "STATUS_ONLINE", 1 );
define( "STATUS_OFFLINE", 2 );
define( "STATUS_AWAY", 3 );
define( "STATUS_BACK", 4 );
define( "STATUS_AUTOAWAY", 5 );

define( "STATUS_FAILURE", 1 );
define( "STATUS_SUCCESS", 2 );

define( "SWIFTPUBLIC", "public" );
define( "SWIFTPRIVATE", "private" );

define( "EDIT", 1 );
define( "INSERT", 2 );
define( "DELETE", 3 );
define( "DISPLAY", 4 );

define( "USERGROUP_GUEST", "guest" );
define( "USERGROUP_REGISTERED", "registered" );
define( "USERGROUP_CUSTOM", "custom" );

define( "LOGINAPI_DEFAULT", 1 );

define( "COMMENT_KNOWLEDGEBASE", 4 );
define( "COMMENT_TROUBLESHOOTER", 6 );
define( "COMMENT_NEWS", 1 );
define( "COMMENT_DOWNLOADS", 5 );

define( "CUSTOMFIELD_USER", 1 );
define( "CUSTOMFIELD_USERGROUP", 2 );
define( "CUSTOMFIELD_STAFFTICKET", 3 );
define( "CUSTOMFIELD_USERTICKET", 4 );
define( "CUSTOMFIELD_STAFFUSERTICKET", 9 );
define( "CUSTOMFIELD_TIMETRACK", 5 );
define( "CUSTOMFIELD_CONTACT", 6 );
define( "CUSTOMFIELD_EVENT", 7 );
define( "CUSTOMFIELD_TASK", 8 );

define( "PRODUCT_SUPPORTSUITE", "SupportSuite" );
define( "PRODUCT_ESUPPORT", "eSupport" );
define( "PRODUCT_LIVERESPONSE", "LiveResponse" );
define( "PRODUCT_HELPBASE", "HelpBase" );

if(!function_exists('file_get_contents')) {
	function file_get_contents($file) {
		return implode('', file($file));
	}
}


class DataStore
{

	var $storecache = array( );
	var $keys = array( );
	var $languagekeys = array( );
	var $languagecache = array( );
	var $languagestorekeys = array( );

	function DataStore( )
	{
		if ( SWIFT_AREA == SWIFT_STAFF || SWIFT_AREA == SWIFT_API )
		{
			$this->keys = array_merge( $this->keys, array( 'staffcache', 'staffgroupcache', 'groupsettingcache', 'staffassigncache', 'groupassigncache', 'departmentcache' ) );
		}
	}

	function loadData( $loadlanguage = false )
	{
		global $registry, $_SWIFT, $template;

		if ( $loadlanguage )
		{
			$keys = &$this->languagekeys;
		}
		else
		{
			$keys = &$this->keys;
		}

		if ( count( $keys ) == 0 )
		{
			return false;
		}

		$this->storecache = $registry->getSelectKeys( $keys );
		reset( $this->storecache );

		while ( list( $key, $val ) = each( $this->storecache ) )
		{
			if ( in_array( $key, $this->languagekeys ) )
			{
				$template->translation = array_merge( $template->translation, unserialize( $val ) );
				$_SWIFT["language"] = &$template->translation;
				$template->clear( "language" );
				$template->assign( "language", $template->translation );
			}
			else
			{
				$_SWIFT[$key] = unserialize( $val );
			}
		}

		$keys = array( );

		return true;
	}

	function cache( $name )
	{
		if ( in_array( $name, $this->keys ) )
		{
			return false;
		}

		$this->keys[] = $name;

		return true;
	}

	function cacheLanguageSection( $section )
	{
		global $_SWIFT;

		$this->languagestorekeys[] = $section;

		return true;
	}

	function cacheLanguage( $languagecode, $section )
	{
		$this->languagecache[] = $languagecode.":".$section;
		$this->languagekeys[] = $languagecode.":".$section;

		return true;
	}

	function load( $name )
	{
		global $registry, $_SWIFT;

		if ( !isset( $this->storecache[$name] ) )
		{
			$this->storecache[$name] = $registry->getKey( $name );

			$_SWIFT[$name] = unserialize( $this->storecache[$name] );
		}

		return true;
	}

	function update( $name, $dataarray, $noshutdown = false )
	{
		global $registry;
		if ( is_array( $dataarray ) )
		{
			$registry->updateKey( $name, serialize( $dataarray ), $noshutdown );
			$_SWIFT[$name] = $dataarray;
		}
	}
}

class dbCore
{

	var $hostname = "";
	var $username = "";
	var $password = "";
	var $name = "";
	var $type = "";
	var $persistent = false;

	var $adodb;

	var $Record = array( );
	var $Record1 = array( );
	var $Record2 = array( );
	var $Record3 = array( );
	var $Record4 = array( );
	var $Record5 = array( );

	var $Row1;
	var $Row2;
	var $Row3;
	var $Row4;
	var $Row5;

	var $linkid = 0;
	var $queryid1 = 0;
	var $queryid2 = 0;
	var $queryid3 = 0;
	var $queryid4 = 0;
	var $queryid5 = 0;

	var $querydb = array( );
	var $querycount = 0;
	var $recordcount = 0;
	var $connected = false;

	function dbCore( $hostname, $username, $password, $dbname, $dbtype, $silent = false, $port = false )
	{
		$this->hostname = $hostname;
		$this->username = $username;
		$this->password = $password;
		$this->name = $dbname;
		$this->dbtype = $dbtype;
		$this->port = $port;

		$this->Record = &$this->Record1;

		if ( !$this->Connect( ) )
		{
			if ( !$silent )
			{
				$this->stop( $this->fetchLastError( ) );
			}
			return false;
		}
		else
		{
			$this->connected = true;
			return true;
		}
	}

	function stop( $errorstr = "" )
	{
		echo "$errorstr";
		exit;
		end;
	}

	function fetchLastError( )
	{
		if ( $this->linkid )
		{
			return mysql_error( $this->linkid );
		}
		return mysql_error( );
	}

	function error( $errorstr )
	{
		if ( !defined( "INSWIFTSETUP" ) )
		{
			echo "$errorstr";
		}
	}

	function Connect( )
	{
		if ( $this->persistent == false )
		{
			$this->linkid = @mysql_connect( $this->hostname.iif( !empty( $this->port ), ":".intval( $this->port ) ), $this->username, $this->password, true );
		}
		else
		{
			$this->linkid = @mysql_pconnect( $this->hostname.iif( !empty( $this->port ), ":".intval( $this->port ) ), $this->username, $this->password, true );
		}
		if ( $this->linkid )
		{
			$selectresult = mysql_select_db( $this->name, $this->linkid );
			if ( !$selectresult )
			{
				return false;
			}
			return true;
		}
		else
		{
			return false;
		}
	}

	function fetchmicrotime( )
	{
		list( $usec, $sec ) = explode( " ", microtime( ) );

		return ( float ) ( ( float )$usec + ( float )$sec );
	}

	function query( $querystr, $id = 1, $issilent = false )
	{
		global $_SWIFT;

		$index = count( $_SWIFT["querydb"] );

		if ( defined( "SWIFTDEBUG" ) )
		{
			$_SWIFT["querydb"][$index]["query"] = $querystr;
			$_SWIFT["querydb"][$index]["start"] = $this->fetchmicrotime( );
		}

		$result = mysql_query( $querystr, $this->linkid );
		$this->{"queryid".$id} = $result;

		if ( defined( "SWIFTDEBUG" ) )
		{
			$_SWIFT["querydb"][$index]["end"] = $this->fetchmicrotime( );
			$_SWIFT["querydb"][$index]["timetaken"] = sprintf( '%.16f', $_SWIFT["querydb"][$index]["end"] - $_SWIFT["querydb"][$index]["start"] );
			$this->recordcount++;
			$this->querycount++;
		}

		if ( !$result )
		{
			if ( defined( "DEBUGSQL" ) )
			{
                            $fp = fopen( "./files/sqllog.txt", "a+" );
                            if ( $fp )
                            {
                            fwrite( $fp, "[".date( "d M Y h:i:s A" )."]: ".$querystr."(".sprintf( '%.16f', $_SWIFT["querydb"][$index]["end"] - $_SWIFT["querydb"][$index]["start"] ).")\n" );
                            fclose( $fp );
                            }
			}

			if ( !$issilent )
			{
				$this->error( "Invalid SQL: ".$querystr." (".mysql_error( $this->linkid ).")" );
			}

			return false;
		}
		else
		{
			return true;
		}
	}

	function queryFetch( $query, $querytcount = 3 )
	{
		$_result = $this->query( $query, $querytcount );
		if ( !$_result )
		{
			return false;
		}

		return $this->nextRecord( $querytcount );
	}

	function nextRecord( $id = 1 )
	{
		$_Query = &$this->{"queryid".$id};

		if ( !$_Query )
		{
			return false;
		}

		$_Record = &$this->{"Record".$id};

		$_Record = @mysql_fetch_array( $_Query, MYSQL_ASSOC );
		if ( is_array( $_Record ) )
		{
			return $_Record;
		}
		else
		{
			return false;
		}
	}

	function shutdownQuery( $query, $noshutdown = false )
	{
		global $_SWIFT;

		if ( !defined( "USESHUTDOWNFUNC" ) )
		{
			$noshutdown = true;
		}

		if ( $noshutdown == true )
		{
			$this->query( $query, 3 );

		}
		else
		{
			if ( defined( "SWIFTDEBUG" ) )
			{
				$index = count( $_SWIFT["querydb"] );
				$_SWIFT["querydb"][$index]["query"] = "(SHUTDOWN) ".$query;
				$_SWIFT["querydb"][$index]["start"] = $this->fetchmicrotime( );
				$_SWIFT["querydb"][$index]["end"] = $this->fetchmicrotime( );
				$_SWIFT["querydb"][$index]["timetaken"] = sprintf( '%.16f', $_SWIFT["querydb"][$index]["end"] - $_SWIFT["querydb"][$index]["start"] );
				$this->recordcount++;
				$this->querycount++;
			}

			$_SWIFT["shutdownquery"][] = $query;
			registerShutdown( "query" );
		}
		return true;
	}

	function lastInsertId( )
	{
		return mysql_insert_id( $this->linkid );
	}

	function debugoutput( )
	{
		global $_SWIFT;

		$debug = "\n\n=========== START PAGE ===========\n\n";
		$count = 0;
		$totaltime = 0;

		for ( $ii = 0; $ii < count( $_SWIFT["querydb"] ); $ii++ )
		{
			$debug .= "---------- QUERY/RECORD START ----------\n";
			$debug .= "ACTION: ".$_SWIFT["querydb"][$ii]["query"]."\n";
			$debug .= "TIME TAKEN: ".$_SWIFT["querydb"][$ii]["timetaken"]." seconds\n";
			$totaltime += $_SWIFT["querydb"][$ii]["timetaken"];
			$count++;
		}

		$debug .= "=========== END PAGE ===========\n";
		$debug .= "TOTAL QUERY COUNT: ".count( $_SWIFT["querydb"] )."\n";
		$debug .= "TOTAL TIME TAKEN FOR QUERIES: ".$totaltime." seconds\n";
		$debug .= "=================================\n";

		echo nl2br( $debug );
	}

	function escape( $data )
	{
		return mysql_real_escape_string( ( string )$data );
	}
}

class Events
{

	var $eventmodules = array( );
	var $events = array( );
	var $eventdata = array( );

	function registerEventModuleSWIFT( $eventname, &$class )
	{
		$this->eventmodules[$eventname] = $class;

		return true;
	}

	function registerEvent( $eventtype, $eventname, $action )
	{
		if ( isset( $this->events[$eventtype][$eventname][$action] ) )
		{
			return false;
		}

		$this->events[$eventtype][$eventname][$action] = true;

		return true;
	}

	function unregisterEvent( $eventtype, $eventname, $eventaction )
	{
		unset($this->events[$eventtype][$eventname][$eventaction]);

		return true;
	}

	function triggerCallback( $eventname, $eventaction, $error = false )
	{
		return $this->execEvent( EVENT_CALLBACK, $eventname, $eventaction, $error );
	}

	function triggerCron( $eventname, $eventaction, $error = false )
	{
		return $this->execEvent( EVENT_CRON, $eventname, $eventaction, $error );
	}

	function execEvent( $eventtype, $eventname, $eventaction, $error = true )
	{
		global $module, $_SWIFT, $settings, $datastore;

		$eventname = cleanVar( $eventname );
		$eventaction = cleanVar( $eventaction );

		if ( trim( $eventname ) != "" )
		{
			if ( !$module->loadModule( $eventname ) )
			{
				if ( $error )
				{
					trigger_error( sprintf( $_SWIFT["language"]["module_notreg"], htmlspecialchars( $eventname ) ), E_USER_ERROR );
				}
				return false;
			}

			if ( !$module->isRegistered( $eventname ) )
			{
				if ( $error )
				{
					trigger_error( sprintf( $_SWIFT["language"]["event_notreg"], htmlspecialchars( $eventname ) ), E_USER_ERROR );
				}
				return false;
			}
			if ( $this->events[$eventtype][$eventname][$eventaction] == true && is_object( $this->eventmodules[$eventname] ) )
			{
				$classexec = &$this->eventmodules[$eventname];
				$_SWIFT["_e"] = $eventaction;

				if ( SWIFT_AREA == SWIFT_CRON )
				{
					$datastore->loadData( false );
				}

				return $classexec->_eventcallback( $eventtype, $eventaction );
			}
			else
                        {
				if($error)
				{
				    trigger_error( sprintf( $_SWIFT["language"]["action_notreg"], htmlspecialchars( $eventaction ) ), E_USER_ERROR );
				}
			}
		}
                else
                {
			return false;
		}
	}

	function getEventData( )
	{
		global $_SWIFT, $argv;

		$data = array( );
		if ( !empty( $this->eventdata["eventname"] ) )
		{
			return $this->eventdata;
		}

		if ( SWIFT_AREA == SWIFT_CLI )
		{
			for ( $ii = 0; $ii < count( $argv ); $ii++ )
			{
				$arraysplit = explode( "=", $argv[$ii] );
				if ( count( $arraysplit ) == 2 )
				{
					$_SWIFT["cli"][$arraysplit[0]] = $arraysplit[1];
				}
			}
			$_eventname = trim( $_SWIFT["cli"]["-m"] );
			$_eventaction = trim( $_SWIFT["cli"]["-a"] );

			if ( $_eventname == "" || $_eventaction == "" )
			{
				return false;
			}

			$data["eventname"] = $_eventname;
			$data["eventaction"] = $_eventaction;
			$_SWIFT["currentmodule"] = $data["eventname"];
			$_SWIFT["currentaction"] = $data["eventaction"];
			$this->eventdata = $data;

			return $this->eventdata;
		}

		if ( isset( $_REQUEST["_m"] ) && isset( $_REQUEST["_a"] ) )
		{
			$data["eventname"] = $_REQUEST["_m"];
			$data["eventaction"] = $_REQUEST["_a"];
			$_SWIFT["currentmodule"] = $data["eventname"];
			$_SWIFT["currentaction"] = $data["eventaction"];
			$this->eventdata = $data;
			return $this->eventdata;
		}
		else if ( isset( $_REQUEST["_m"] ) && !isset( $_REQUEST["_a"] ) )
		{
			return false;
		}
		else
		{
			return false;
                }
	}

	function triggerEvent( $eventtype )
	{
		global $module, $_SWIFT;

		if ( !$this->getEventData( ) )
		{
			return false;
		}
		else
		{
			return $this->execEvent( $eventtype, $this->eventdata["eventname"], $this->eventdata["eventaction"] );
		}
	}
}

class Module
{

	var $registered = array( );
	var $available = array( );
	var $loaded = array( );

	function Module( )
	{
		global $settings, $_SWIFT, $events;

		if ( $events->getEventData( )){
			if(!$this->loadModule( $events->eventdata["eventname"] ) )
			{
			    trigger_error( sprintf( $_SWIFT["language"]["unable_to_execute"], htmlspecialchars( $events->eventdata["eventname"] ) ), E_USER_ERROR );
			}
		}

		$_SWIFT["registeredmodules"] = &$this->registered;
	}

	function loadModule( $name )
	{
		global $_MODULES;

		$name = cleanVar( $name );

		if ( in_array( $name, $this->loaded ) )
		{
			return true;
		}

		$modulefile = $_MODULES[$name];

		if ( file_exists( $modulefile ) )
		{
			require_once( $modulefile );

			eval( 'global $'.$name.'; $'.$name.' = new '.$name.';' );
			registerShutdown( "modules" );
			$this->loaded[] = $name;

			return true;
		}
		else
		{
			return false;
		}
	}

	function listModules( )
	{
		$this->available = array( );

		if ( $handle = opendir( "./modules" ) )
		{
			while ( false !== ( $file = readdir( $handle ) ) )
			{
				if ( $file != "." && $file != ".." && is_dir( "./modules/".$file ) )
				{
					$this->available[] = $file;
				}
			}

			closedir( $handle );
		}

		return $this->available;
	}

	function registerModule( $modulename )
	{
		global $settings;

		if ( $this->moduleExists( $modulename ) && !$this->isRegistered( $modulename ) && $this->loadModule( $modulename ) )
		{
			$settings->insertKey( "registeredmodules", $modulename, "1", true );

			return true;
		}
		else
		{
			return false;
                }
	}

	function unregisterModule( $modulename )
	{
		global $settings;

		if ( $this->moduleExists( $modulename ) && $this->isRegistered( $modulename ) && $this->loadModule( $modulename ) )
		{
			$settings->deleteKey( "registeredmodules", $modulename );

			return true;
		}
		else
		{
			return false;
                }
	}

	function moduleExists( $modulename )
	{
		$this->listModules( );
		if ( !in_array( $modulename, $this->available ) )
		{
			return true;
		}
		else
		{
			return false;
                }
	}

	function isRegistered( $modulename )
	{
		global $settings;

		if ( $this->registered[$modulename] == "1" )
		{
			return true;
		}
		else
		{
			return false;
                }
	}

	function isLoaded( $modulename )
	{
		if ( in_array( $modulename, $this->loaded ) )
		{
			return true;
		}
		else
		{
			return false;
                }
	}
}

class Registry
{

	var $cache = array( );
	var $cachekey = array( );
	var $noshutdown = false;

	function insertKey( $key, $data = "", $noshutdown = false )
	{
		global $dbCore;

		$dbCore->shutdownQuery( "INSERT INTO `".TABLE_PREFIX."registry` (`vkey`, `data`, `dateline`, `isvolatile`, `datasize`) VALUES('".$dbCore->escape( $key )."', '".$dbCore->escape( $data )."', '".DATENOW."', '0', '".strlen( $data )."')", $noshutdown );

		$this->cache[$key] = $data;

		return true;
	}

	function updateKey( $key, $data = "", $noshutdown = false )
	{
		global $dbCore;

		if ( $data != "" )
		{
			$return = $this->getKey( $key );
			if ( $return != "" )
			{
				$dbCore->shutdownQuery( "UPDATE `".TABLE_PREFIX."registry` SET `data` = '".$dbCore->escape( $data )."', `datasize` = '".strlen( $data )."' WHERE `vkey` = '".$dbCore->escape( $key )."'", $noshutdown );
				$this->cache[$key] = $data;

				return true;
			}
			else
			{
				return $this->insertKey( $key, $data, $noshutdown );
			}
		}
                else
		{
			return $this->deleteKey( $key );
		}
	}

	function deleteKey( $key, $noshutdown = false )
	{
		global $dbCore;

		$dbCore->shutdownQuery( "DELETE FROM `".TABLE_PREFIX."registry` WHERE `vkey` = '".$dbCore->escape( $key )."'", $noshutdown );

		unset( $this->cache[$key] );

		return true;
	}

	function deleteKeyList( $keylist, $noshutdown = false )
	{
		global $dbCore;

		if ( !is_array( $keylist ) || !count( $keylist ) )
		{
			return false;
		}

		$dbCore->shutdownQuery( "DELETE FROM `".TABLE_PREFIX."registry` WHERE `vkey` IN (".buildIN( $keylist ).");", $noshutdown );

		for ( $ii = 0; $ii < count( $keylist ); $ii++ )
		{
			unset( $this->cache[$keylist[$ii]] );
		}
	}

	function getKey( $key )
	{
		global $dbCore;

		if ( !empty( $this->cache[$key] ) )
		{
			return $this->cache[$key];
		}

		$dbCore->query( "SELECT `data` FROM `".TABLE_PREFIX."registry` WHERE `vkey` = '".$dbCore->escape( $key )."';", 5 );
		$dbCore->nextRecord( 5 );

		if ( $dbCore->Record5["data"] != "" )
		{
			$this->cache[$key] = $dbCore->Record5["data"];

			return $dbCore->Record5["data"];
		}
		else
		{
			return false;
                }
	}

	function getSelectKeys( $keyarray )
	{
		global $dbCore;

		$store = array( );

		$dbCore->query( "SELECT `vkey`, `data` FROM `".TABLE_PREFIX."registry` WHERE `vkey` IN(".buildIN( $keyarray ).");", 5 );
		while ( $dbCore->nextRecord( 5 ) )
		{
			$store[$dbCore->Record5["vkey"]] = $dbCore->Record5["data"];
			$this->cache[$dbCore->Record5["vkey"]] = $dbCore->Record5["data"];
		}

		return $store;
	}
}

class Session
{
	var $sessionid = "";
	var $useragent = "";
	var $ipaddress = "";
	var $dateline = "";
	var $isloggedin = false;
	var $sessiontype = false;

	var $_S = array();

	function Session()
	{
		$this->ipaddress = $_SERVER["REMOTE_ADDR"];
		$this->useragent = trim(substr($_SERVER["HTTP_USER_AGENT"], 0, 60));
	}

	function start($sessiontype)
	{
		global $_SWIFT, $dbCore, $cookie, $staffauth, $settings, $template;

		$cookiesid  = cleanVar($cookie->getSCookie("sessionid".$sessiontype));

		if (!empty($_POST["sessionid"]))
		{
			$sessionid = cleanVar($_POST["sessionid"]);
		}
                else if (!empty($_GET["sessionid"]))
                {
			$sessionid = cleanVar($_GET["sessionid"]);
		}
                else if (!empty($cookiesid))
                {
			$sessionid = &$cookiesid;
		}
		else if ( defined( "DEBUGSESSIONEXPIRY" ) )
		{
			echo "[Session Expired Debug]: Unable to find session id in POST, GET or COOKIE variable.. Clearing Out...";
		}
		else
		{
			return false;
		}

                if (!$this->fetchSession($sessionid, $sessiontype))
		{
			$cookie->emptySCookie("sessionid".$sessiontype);
			$_SWIFT["errorstr"] = $_SWIFT["language"]["invalid_sessionid"];

			if ( defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: Unable to fetch a valid session for session id: ".$sessionid;
			}

			return false;

		}

                if (empty ($_GET["sessionid"]) && empty ($cookiesid) && $sessiontype == SESSION_STAFF)
                {
                $cookie->setSCookie ("sessionid" . $sessiontype, $sessionid);
                }

		if ($sessiontype == SESSION_CLIENT || $sessiontype == SESSION_VISITOR)
		{
		if (!empty($_SWIFT["session"]["typeid"]))
			{
				$_SWIFT["usergroupid"] = $_SWIFT["tgroup"]["regusergroupid"];
			}
			else
			{
				$_SWIFT["usergroupid"] = $_SWIFT["tgroup"]["guestusergroupid"];
			}
		}

		$template->assign("session", &$_SWIFT["session"]);

		if ($sessiontype != SESSION_ADMIN && $sessiontype != SESSION_STAFF && $sessiontype != SESSION_WINAPP && $sessiontype != SESSION_API && $sessiontype != SESSION_WAP && $sessiontype != SESSION_MONITOR && $sessiontype != SESSION_PDA && $sessiontype != SESSION_SYNCWORKS && $sessiontype != SESSION_INSTAALERT && $sessiontype != SESSION_MOBILE)
		{
			return true;
		}

		if (!$staffauth->loadStaff($this->typeid))
		{
			$this->flushSession($sessionid, $sessiontype);

			if ( defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: Unable to load any staff user for type id: ".$this->typeid;
			}

			return false;
		}
			if (($sessiontype == SESSION_ADMIN || $sessiontype == SESSION_API) && $_SWIFT["staff"]["isadmin"] != "1")
		{
			$this->flushSession($sessionid, $sessiontype);
			$_SWIFT["errorstr"] = $_SWIFT["language"]["staff_not_admin"];

			if ( defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: User isnt admin and is trying to login to Admin CP.. bailing out..";
			}

			return false;
		}

		if ($settings->store["security_sessioninactivity"] != "0" && ((DATENOW - $this->_S["lastactivity"]) > $settings->store["security_sessioninactivity"] && $_S["lastactivity"] != 0))
		{
			$this->flushSession($this->_S["sessionid"], $this->_S["sessiontype"]);
			$_SWIFT["errorstr"] = $_SWIFT["language"]["invalid_sessionid"];

			if ( defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: Session expired due to inactivity, Date difference between current system date (".date( "d M Y h:i:s A", DATENOW ).") and last activity (".date( "d M Y h:i:s A", $this->_S["lastactivity"] ).") is ".( DATENOW - $this->_S["lastactivity"] )." seconds whereas inactivity timing setting under Admin CP > Settings is ".$settings->store["security_sessioninactivity"]." seconds.";
			}

			return false;
		}

		if ((DATENOW - $_SWIFT["staff"]["lastactivity"]) > 180)
		{
			$staffauth->updateLastActivity($_SWIFT["staff"]["staffid"]);
		}
	if ((DATENOW - $_SWIFT["staff"]["lastvisit2"]) > 1800)
		{
			$staffauth->updateLastVisit($_SWIFT["staff"]["staffid"]);
		}

		return true;
	}

	function startSyncMLSession($sessionid, $useragent)
	{
		global $_SWIFT, $dbCore, $cookie, $staffauth, $settings;

		$this->useragent = $useragent;

		if (!$this->fetchSession($sessionid, SESSION_SYNCML))
		{
			return false;
		}

		if (!$staffauth->loadStaff($this->typeid))
		{
			$this->flushSession($sessionid, SESSION_SYNCML);

			return false;
		}

		if ($settings->store["security_sessioninactivity"] != "0" && ((DATENOW - $this->_S["lastactivity"]) > $settings->store["security_sessioninactivity"]))
		{
			$this->flushSession($this->_S["sessionid"], $this->_S["sessiontype"]);

			return false;
		}

		return true;
	}

	function fetchSession($sessionid, $sessiontype)
	{
		global $dbCore, $_SWIFT;

		$_S = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."sessions` WHERE sessionid = '". $dbCore->escape($sessionid) ."';");

		if (trim($_S["useragent"]) != trim($this->useragent) && ($sessiontype != SESSION_WINAPP && $sessiontype != SESSION_STAFF && $sessiontype != SESSION_SYNCWORKS && $sessiontype != SESSION_INSTAALERT))
		{
			$noproceed = true;
		}
		else
		{
                        $useragentfailed = true;
			$noproceed = false;
		}

		if ($_S["sessiontype"] == $sessiontype && !$noproceed)
		{
			if ($sessiontype != SESSION_SYNCML && $_S["ipaddress"] != $this->ipaddress && $_SWIFT["disablesessionipcheck"] != true)
			{
				return false;
			}
                        else if (($sessiontype == SESSION_STAFF || $sessiontype == SESSION_WAP || $sessiontype == SESSION_WINAPP || $sessiontype == SESSION_ADMIN || $sessiontype == SESSION_PDA) && empty($_S["typeid"]))
                        {
				if ( defined( "DEBUGSESSIONEXPIRY" ) )
				{
				echo "[Session Expired Debug]: No Valid TypeID FOUND!.";
				}

                        return false;
			}

			$this->sessionid = $_S["sessionid"];
			$_SWIFT["sessionid"] = $_S["sessionid"];
			$_SWIFT["sessionstarted"] = true;
			$this->lastactivity = $_S["lastactivity"];
			$this->isloggedin = $_S["isloggedin"];
			$this->sessiontype = $sessiontype;
			$this->dateline = $_S["dateline"];
			$this->typeid = $_S["typeid"];
			$this->_S = $_S;
			$_SWIFT["session"] = &$this->_S;

			unset($_S);
			$sessionidlist = array();
			$sessionidlist[] = $sessionid;

			if ($sessiontype == SESSION_WINAPP && !empty($_POST["staffsessionid"]))
			{
				$sessionidlist[] = $_POST["staffsessionid"];
			}

			if ($sessiontype != SESSION_VISITOR)
			{
                                $dbCore->query ("UPDATE `" . TABLE_PREFIX . "sessions` SET `lastactivity` = '" . $dbCore->escape (DATENOW) . "'" . iif ((!empty ($_REQUEST["status"]) && ($sessiontype || $sessiontype == SESSION_WINAPP)), ", `status` = '" . $dbCore->escape ($_REQUEST["status"]) . "'") . " WHERE `sessionid` IN (" . buildIN ($sessionidlist) . ");", false);
			}

			return true;
		}
		else
		{
			if ( $useragentfailed && defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: User Agent Doesnt Match!! Current: ".trim( $this->useragent ).", DB Stored Value: ".$_S["useragent"];
			}

			if ( defined( "DEBUGSESSIONEXPIRY" ) )
			{
			echo "[Session Expired Debug]: Session type doesnt match.. Current: ".$sessiontype.", DB Stored Value: ".$_S["sessiontype"];
			}

			return false;
		}
	}

	function updateSession($sessionid, $typeid)
	{
		global $dbCore, $_SWIFT;

		$dbCore->query("UPDATE `". TABLE_PREFIX."sessions` SET `typeid` = '". $dbCore->escape($typeid) ."' WHERE `sessionid` = '". $dbCore->escape($sessionid) ."';");
	}

	function insertSession($sessiontype, $typeid = 0, $customsessionid = "", $noshutdown = false)
	{
		global $dbCore, $_SWIFT, $cookie;

		if ($customsessionid != "")
		{
			$sessionid = $customsessionid;
		}
		else
		{
			$sessionid = buildHash();
		}

		if ($sessiontype == SESSION_WINAPP || $sessiontype == SESSION_ADMIN || $sessiontype == SESSION_API || $sessiontype == SESSION_WAP || $sessiontype == SESSION_SYNCML || $sessiontype == SESSION_MONITOR || $sessiontype == SESSION_PDA || $sessiontype == SESSION_SYNCWORKS || $sessiontype == SESSION_MOBILE)
		{
			if (!empty($typeid))
			{
				$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `ipaddress` = '". $dbCore->escape($_SWIFT["IP"]) ."' AND `sessiontype` = '". $dbCore->escape($sessiontype) ."' AND `typeid` = '". intval($typeid) ."';", $noshutdown);
				$isloggedin = "1";
			}
			else
			{
				return false;
			}
		}
                else if ($sessiontype == SESSION_STAFF || $sessiontype == SESSION_INSTAALERT)
                {
			if (!empty($typeid))
			{
				$cleartime = DATENOW - $_SWIFT["settings"]["security_sessioninactivity"];
				$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `sessiontype` = '". intval($sessiontype) ."' AND `lastactivity` < '". $dbCore->escape($cleartime) ."';");

				$isloggedin = "1";
			}
			else
			{
				return false;
			}
		}
                else if ($sessiontype == SESSION_VISITOR)
                {
			$isloggedin = "0";

			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `ipaddress` = '". $dbCore->escape($_SWIFT["IP"]) ."' AND `sessiontype` = '". $dbCore->escape($sessiontype) ."';", $noshutdown);
			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."visitorfootprints` WHERE `ipaddress` = '". $dbCore->escape($_SWIFT["IP"]) ."';", $noshutdown);
		}
                else if ($sessiontype == SESSION_CLIENT)
                {
			$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `ipaddress` = '". $dbCore->escape($_SWIFT["IP"]) ."' AND `sessiontype` = '". $dbCore->escape($sessiontype) ."';", $noshutdown);
		}
		else if ($sessiontype == SESSION_CHAT)
		{

		}
		else
		{
			return false;
		}

		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."sessions` (`sessionid`, `ipaddress`, `lastactivity`, `useragent`, `isloggedin`, `sessiontype`, `typeid`, `dateline`, `status`) VALUES('". $dbCore->escape($sessionid) ."', '". $dbCore->escape($_SWIFT["IP"]) ."', '". DATENOW ."', '". $dbCore->escape(substr($this->useragent, 0, 60)) ."', '". intval($isloggedin) ."', '". $dbCore->escape($sessiontype) ."', '". $dbCore->escape($typeid) ."', '". DATENOW ."', '". iif($sessiontype==SESSION_WINAPP, STATUS_ONLINE, "0") ."');", $noshutdown);

		if ($sessiontype != SESSION_CHAT)
		{
			$_SWIFT["sessionid"] = $sessionid;
			$_SWIFT["session"]["sessionid"] = $sessionid;
			$_SWIFT["session"]["ipaddress"] = $_SERVER["REMOTE_ADDR"];
			$_SWIFT["session"]["lastactivity"] = DATENOW;
			$_SWIFT["session"]["useragent"] = $_SERVER["HTTP_USER_AGENT"];
			$_SWIFT["session"]["isloggedin"] = "1";
			$_SWIFT["session"]["sessiontype"] = $sessiontype;
			$_SWIFT["session"]["typeid"] = $typeid;
			$_SWIFT["session"]["dateline"] = DATENOW;

			$cookie->setSCookie("sessionid".$sessiontype, $sessionid);
		}

		return $sessionid;
	}

function insertCustomSession($sessiontype, $typeid = 0, $iswinapp = 0)
	{
		global $dbCore, $_SWIFT, $cookie;

		$sessionid = buildHash();

		if (!empty($typeid))
		{
			$isloggedin = true;
		}

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."sessions` (`sessionid`, `ipaddress`, `lastactivity`, `useragent`, `isloggedin`, `sessiontype`, `typeid`, `dateline`, `status`, `iswinapp`) VALUES('". $dbCore->escape($sessionid) ."', '". $dbCore->escape($_SWIFT["IP"]) ."', '". DATENOW ."', '". $dbCore->escape(substr($this->useragent, 0, 60)) ."', '". $dbCore->escape($isloggedin) ."', '". $dbCore->escape($sessiontype) ."', '". $dbCore->escape($typeid) ."', '". DATENOW ."', '". iif($sessiontype==SESSION_WINAPP, STATUS_ONLINE, "0") ."', '". intval($iswinapp) ."');");

		$cookie->setSCookie("sessionid".$sessiontype, $sessionid);

		return $sessionid;
	}

	
	function logoutSession($sessiontype)
	{
		global $cookie;

		$cookiesid  = cleanVar($cookie->getSCookie("sessionid".$sessiontype));

		if (!empty($_POST["sessionid"]))
		{
			$sessionid = cleanVar($_POST["sessionid"]);
		}
                else if (!empty($_GET["sessionid"]))
                {
			$sessionid = cleanVar($_GET["sessionid"]);
		}
                else if (!empty($cookiesid))
                {
			$sessionid = &$cookiesid;
		}
		else
		{
			
			return false;
		}

		if (trim($sessionid) != "")
		{
			$this->flushSession($sessionid, $sessiontype);

			return true;
		}
		else
		{

			return false;
		}
	}

	function flushSession($sessionid, $sessiontype)
	{
		global $dbCore, $_SWIFT, $cookie;

		if (empty($sessionid))
		{
			return;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `sessionid` = '". $dbCore->escape($sessionid) ."';");

		unset($this->sessionid);
		unset($this->lastactivity);
		unset($this->isloggedin);
		unset($this->sessiontype);
		unset($this->dateline);
		unset($this->typeid);
		unset($this->_S);
		unset($_SWIFT["sessionid"]);
		unset($_SWIFT["session"]);
		$cookie->emptySCookie("sessionid".$sessiontype);
		$_SWIFT["sessionstarted"] = false;
	}

	function deleteSession($sessionid, $sessiontype)
	{
		global $dbCore, $_SWIFT, $cookie;

		if (empty($sessionid))
		{
			return;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `sessionid` = '". $dbCore->escape($sessionid) ."';");

		$cookie->emptySCookie("sessionid".$sessiontype);
	}

	function flushInactiveSessions()
	{
		global $dbCore, $_SWIFT;

		$cleartime = DATENOW - $_SWIFT["settings"]["security_sessioninactivity"];
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."sessions` WHERE `lastactivity` < '". $dbCore->escape($cleartime) ."';");

		return true;
	}
}

class Cookie
{

	var $cookies;

	function getSCookie( $name )
	{
		return $_COOKIE["SWIFT_".$name];
	}

	function setSCookie( $name, $value, $permanent = false )
	{
		global $_SWIFT;

		if ( $permanent )
		{
			$expiry = DATENOW + 60*60*24*365;

			SetCookie( "SWIFT_".$name, $value, $expiry, iif( $_SWIFT["settings"]["security_cookiepath"] == "", "/", $_SWIFT["settings"]["security_cookiepath"] ), iif( $_SWIFT["settings"]["security_cookiedomain"] == "", "", $_SWIFT["settings"]["security_cookiedomain"] ) );
		}
		else
		{
			SetCookie( "SWIFT_".$name, $value, $expiry, iif( $_SWIFT["settings"]["security_cookiepath"] == "", "/", $_SWIFT["settings"]["security_cookiepath"] ), iif( $_SWIFT["settings"]["security_cookiedomain"] == "", "", $_SWIFT["settings"]["security_cookiedomain"] ) );
		}
		return true;
	}

	function emptySCookie( $name )
	{
		global $_SWIFT;

                SetCookie( "SWIFT_".$name, "", 0, iif( $_SWIFT["settings"]["security_cookiepath"] == "", "/", $_SWIFT["settings"]["security_cookiepath"] ), iif( $_SWIFT["settings"]["security_cookiedomain"] == "", "", $_SWIFT["settings"]["security_cookiedomain"] ) );
                unset( $_COOKIE["SWIFT_".$name] );

                return true;
	}

	function addCookie( $name, $key, $value )
	{
		$this->cookies["SWIFT_".$name][$key] = $value;

		return true;
	}

	function buildCookie( $name, $permanent = false )
	{
		global $_SWIFT;

		$this->setSCookie( $name, serialize( $this->cookies["SWIFT_".$name] ), $permanent );
		return true;
	}

	function parseCookie( $name )
	{
		$this->cookies["SWIFT_".$name] = unserialize( $_COOKIE["SWIFT_".$name] );
		if ( is_array( $this->cookies["SWIFT_".$name] ) )
		{
			return true;
		}
                else
                {
                        return false;
                }
	}

	function emptyCookie( $name )
	{
		global $_SWIFT;

		SetCookie("SWIFT_".$name, "", $expiry, iif($_SWIFT["settings"]["security_cookiepath"]=="", "/", $_SWIFT["settings"]["security_cookiepath"]), iif($_SWIFT["settings"]["security_cookiedomain"]=="", "", $_SWIFT["settings"]["security_cookiedomain"]));

		unset($this->cookies["SWIFT_".$name]);

		return true;
	}

	function getKey( $cookiename, $keyname )
	{
		return $this->cookies["SWIFT_".$cookiename][$keyname];
	}
}

class Settings
{

	var $data = array( );
	var $store = array( );

	function Settings( )
	{
		global $dbCore, $registry, $_SWIFT;

		$_SWIFT["shutdown"]["settings"] = 0;
		if ( isset( $_SWIFT["settingscache"] ) )
		{
			$this->data = &$_SWIFT["settingscache"];
			$this->store = &$this->data["settings"];
			$_SWIFT["settings"] = &$this->data["settings"];
			return true;
		}
                else
                {
		return false;
                }
	}

	function updateKey( $section, $key, $data = "", $noshutdown = false )
	{
		global $dbCore;

		if ( $data != "" )
		{
			$dbCore->query( "SELECT `section`, `vkey` FROM `".TABLE_PREFIX."settings` WHERE `section` = '".$dbCore->escape( $section )."' AND `vkey` = '".$dbCore->escape( $key )."'", 5 );
			$dbCore->nextRecord( 5 );

			if ( $dbCore->Record5["section"] == $section && $dbCore->Record5["vkey"] == $key )
			{
				$dbCore->shutdownQuery( "UPDATE `".TABLE_PREFIX."settings` SET `data` = '".$dbCore->escape( $data )."' WHERE `section` = '".$dbCore->escape( $section )."' AND `vkey` = '".$dbCore->escape( $key )."'", $noshutdown );

				if ( $noshutdown )
				{
					$this->rebuildArray( );
				}
				else
				{
					registerShutdown( "settings" );
				}

				return true;
			}
			else
			{
				return $this->insertKey( $section, $key, $data );
			}
                }
		else
		{
			return $this->deleteKey( $section, $key );
		}
        }

			function insertKey( $section, $key, $data = "", $noshutdown = false )
			{
				global $dbCore;

				$dbCore->shutdownQuery( "INSERT INTO `".TABLE_PREFIX."settings` (`section`, `vkey`, `data`) VALUES('".$dbCore->escape( $section )."', '".$dbCore->escape( $key )."', '".$dbCore->escape( $data )."')", $noshutdown );

				registerShutdown( "settings" );

				return true;
			}

			function deleteKey( $section, $key, $noshutdown = false )
			{
				global $dbCore;

				$dbCore->shutdownQuery( "DELETE FROM `".TABLE_PREFIX."settings` WHERE `section` = '".$dbCore->escape( $section )."' AND `vkey` = '".$dbCore->escape( $key )."'", $noshutdown );

				registerShutdown( "settings" );

				return true;
			}

			function deleteSection( $section, $noshutdown = false )
			{
				global $dbCore;

				$dbCore->shutdownQuery( "DELETE FROM `".TABLE_PREFIX."settings` WHERE `section` = '".$dbCore->escape( $section )."'", $noshutdown );

				registerShutdown( "settings" );

				return true;
			}

			function rebuildArray( )
			{
				global $dbCore, $registry;

				$settingstore = array( );

				$dbCore->query( "SELECT `section`, `vkey`, `data` FROM `".TABLE_PREFIX."settings` ORDER BY `settingid` ASC;", 5 );
				while ( $dbCore->nextRecord( 5 ) )
				{
					$unserarray = @unserialize( $dbCore->Record5["data"] );
					if ( is_array( $unserarray ) )
					{
						$settingstore[$dbCore->Record5["section"]][$dbCore->Record5["vkey"]] = $unserarray;
					}
					else
					{
						$settingstore[$dbCore->Record5["section"]][$dbCore->Record5["vkey"]] = $dbCore->Record5["data"];
					}
				}

				$this->data = $settingstore;

				$registry->updateKey( "settingscache", serialize( $settingstore ), true );

				return true;
			}

			function getKey( $section, $key )
			{
				if ( isset( $this->data[$section][$key] ) )
				{
					return $this->data[$section][$key];
				}
				else
				{
					return false;
                                }
			}

			function getSection( $section )
			{
				if ( isset( $this->data[$section] ) )
				{
					return $this->data[$section];
				}
				else
				{
					return false;
				}
			}
}

class StaffAuth
{

	function authenticate( $username, $password, $shouldbeadmin = false, $usemd5 = true )
	{
		global $dbCore, $_SWIFT;

		if ( $usemd5 == true )
		{
			$finalpassword = md5( $password );
		}
		else
		{
			$finalpassword = &$password;
		}
		$staff = $dbCore->queryFetch( "SELECT staff.*, staffgroup.* FROM `".TABLE_PREFIX."staff` AS staff LEFT JOIN `".TABLE_PREFIX."staffgroup` AS staffgroup ON(staff.staffgroupid = staffgroup.staffgroupid) WHERE staff.username = '".$dbCore->escape( $username )."' AND staff.password = '".$dbCore->escape( $finalpassword )."';" );

		if ( !empty( $staff["staffid"] ) )
		{
			if ( $shouldbeadmin == true && $staff["isadmin"] == "1" )
			{
				$this->updateLastVisit( $staff["staffid"] );
				return $staff["staffid"];
			}
			else if ( $shouldbeadmin == true && $staff["isadmin"] != "1" )
			{
				$_SWIFT["errorstr"] = $_SWIFT["language"]["staff_not_admin"];
				return false;
			}
			else if ( ( $shouldbeadmin == false ) )
			{
				$this->updateLastVisit( $staff["staffid"] );
				return $staff["staffid"];
			}
		}
		else
		{
			$_SWIFT["errorstr"] = $_SWIFT["language"]["invaliduser"];
			return false;
		}

	}

	function loadStaff( $staffid )
	{
		global $_SWIFT, $dbCore, $template;

		if ( is_array( $_SWIFT["staff"] ) )
		{
			return true;
		}

		$_staff = $dbCore->queryFetch( "SELECT staff.*, staffgroup.*, staffgroup.title AS grouptitle, signatures.signature FROM `".TABLE_PREFIX."staff` AS staff LEFT JOIN `".TABLE_PREFIX."signatures` AS signatures ON (staff.staffid = signatures.staffid) LEFT JOIN `".TABLE_PREFIX."staffgroup` AS staffgroup ON(staff.staffgroupid = staffgroup.staffgroupid) WHERE staff.staffid = '".intval( $staffid )."';" );

		$staffgroupid = $_staff["staffgroupid"];
		$_SWIFT["staff"] = array_merge( $_staff, $_SWIFT["groupsettingcache"][$staffgroupid] );

		if ( !is_array( $_SWIFT["staff"] ) )
		{
			return false;
		}
		else
		{
			$template->assign( "staffname", $_staff["fullname"] );
			if ( $_SWIFT["staff"]["timezoneoffset"] != "99" )
			{
				$_SWIFT["timezone"] = $_SWIFT["staff"]["timezoneoffset"];
				$_SWIFT["daylightsavings"] = iif( $_SWIFT["staff"]["enabledst"] == true, true, false );
			}
			return true;
		}
	}

	function updateLastActivity( $staffid )
	{
		global $_SWIFT, $dbCore;

		return $dbCore->shutdownQuery( "UPDATE LOW_PRIORITY `".TABLE_PREFIX."staff` SET `lastactivity` = '".$dbCore->escape( DATENOW )."' WHERE `staffid` = '".intval( $staffid )."';" );
	}

	function updateLastVisit( $staffid )
	{
		global $_SWIFT, $dbCore;

		return $dbCore->shutdownQuery( "UPDATE LOW_PRIORITY `".TABLE_PREFIX."staff` SET `lastvisit` = `lastvisit2`, `lastvisit2` = '".$dbCore->escape( DATENOW )."' WHERE `staffid` = '".intval( $staffid )."';" );
	}

	function displayLoginForm( $error )
	{
		global $template, $_SWIFT, $cookie;

		if ( !empty( $_SERVER["QUERY_STRING"] ) )
		{
			$template->assign( "querystring", iif( !stristr( $_SERVER["QUERY_STRING"], "logout" ), $_SERVER["QUERY_STRING"] ) );
		}
		else if ( !empty( $_POST["querystring"] ) )
		{
			$template->assign( "querystring", iif( !stristr( $_POST["querystring"], "logout" ), $_POST["querystring"] ) );
		}
		$template->assign( "error", $error );

		if ( SWIFT_AREA == SWIFT_ADMIN )
		{
			$_remusername = $cookie->getSCookie( "remusernameadm" );

			$template->assign( "username", $_remusername );
			$template->assign( "cookiepassword", $cookie->getSCookie( "rempasswordadm" ) );
		}
		else
		{
			$_remusername = $cookie->getSCookie( "remusername" );

			$template->assign( "username", $_remusername );
			$template->assign( "cookiepassword", $cookie->getSCookie( "rempassword" ) );
		}
		if ( !empty( $_remusername ) )
		{
			$template->assign( "remember", true );
			$template->assign( "password", "******" );
		}
		else
		{
			$template->assign( "remember", false );
		}

		echo $template->displayTemplate( "loginform.tpl" );
	}

	function isAdmin( )
	{
		global $_SWIFT;

		if ( $_SWIFT["staff"]["isadmin"] == 1 )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

class CPInterface
{
	var $quicklinks = array( );
	var $itemoptions = array( );

	function CPInterface( )
	{
		global $template;
		$template->register_function( "processCPMenu", "tpl_function_processCPMenu" );
		$template->register_function( "processCPAdminNavBar", "tpl_function_processCPAdminNavBar" );
	}

	function adminHeader( $title, $selectedmenu = 1 )
	{
		global $_SWIFT, $template;

		$template->assign( "area", "admin" );
		$template->assign( "title", $title." - ".sprintf( $_SWIFT["language"]["poweredby"], SWIFTPRODUCT ) );

		$template->assign( "menucount", count( $_SWIFT["adminmenu"] ) );
		$template->assign( "menucolspan", count( $_SWIFT["adminmenu"] ) + 2 );
		$template->assign( "menu", &$_SWIFT["adminmenu"] );

		$template->assign( "menulinks", &$_SWIFT["adminlinks"] );
		$template->assign( "selectedmenu", $selectedmenu );
		$template->assign( "selectedmenuclass", $selectedmenu );

		$this->processOnlineUsers( );

		echo $template->displayTemplate( "cpheader.tpl" );
	}

	function adminFooter( )
	{
		global $template, $dbCore;

		echo $template->displayTemplate( "admincpfooter.tpl" );
	}

	function staffHeader( $title, $selectedmenu = 1 )
	{
		global $_SWIFT, $template, $module, $dbCore;

		$template->assign( "area", "staff" );
		$template->assign( "title", $title." - ".sprintf( $_SWIFT["language"]["poweredby"], SWIFTPRODUCT ) );

		$finalstaffmenu = $finalstafflinks = $dropdownlist = array( );
		$index = $menuclass = 1;
		foreach ( $_SWIFT["staffmenu"] as $key => $val )
		{
			$settingcheck = $val[4];
			if ( $module->isRegistered( $val[2] ) && ( $settingcheck == "" || $_SWIFT["settings"][$settingcheck] == "1" || $_SWIFT["settings"][$settingcheck] == "" ) && ( $_SWIFT["staff"][$settingcheck] != "0" ) ) {

			for ( $kk = 0; $kk < count( $_SWIFT["stafflinks"][$key] ); $kk++ )
			{
				if ( is_array( $_SWIFT["stafflinks"][$key][$kk][4] ) && count( $_SWIFT["stafflinks"][$key][$kk][4] ) == 2 )
				{
					$dropdownlist[count( $dropdownlist )] = $_SWIFT["stafflinks"][$key][$kk][4];
				}
			}

			$finalstaffmenu[$key] = $_SWIFT["staffmenu"][$key];
			$finalstafflinks[$key] = $_SWIFT["stafflinks"][$key];

			if ( $menuclass > 6 )
			{
				$menuclass = 1;
			}

			if ( $key == $selectedmenu && !empty( $menuclass ) )
			{
				$selectedmenuclass = $menuclass;
			}

			$finalstaffmenu[$key][3] = $menuclass;

			$index++;
			$menuclass++;
                        }
                }

		$template->assign( "menucount", count( $finalstaffmenu ) );
		$template->assign( "menucolspan", count( $finalstaffmenu ) + 2 );
		$template->assign( "menu", $finalstaffmenu );
		$template->assign( "dropdown", $_SWIFT["staffdropmenu"] );
		$template->assign( "dropdownlist", $dropdownlist );

		$_filtereddep = array( );

		foreach ( $_SWIFT["departmentcache"] as $key => $val )
		{
			$_filtereddep[$key] = $val;
			$_filtereddep[$key]["title"] = addslashes( $val["title"] );
		}

		$template->assign( "cpdepartments", $_filtereddep );
		$template->assign( "cpdepcount", count( $_SWIFT["departmentcache"] ) );

		$template->assign( "menulinks", $finalstafflinks );
		$template->assign( "selectedmenu", $selectedmenu );
		$template->assign( "selectedmenuclass", $selectedmenuclass );

		$this->processOnlineUsers( );

		echo $template->displayTemplate( "cpheader.tpl" );
	}

	function processOnlineUsers( )
	{
		global $dbCore, $_SWIFT, $template;

		$onlinelist = $staffidlist = $_staffidlist = array( );
		$index = 0;
		$activitythreshold = DATENOW - 180;

		$dbCore->query( "SELECT `sessiontype`, `typeid`, `lastactivity` FROM `".TABLE_PREFIX."sessions` WHERE `sessiontype` IN ('".SESSION_STAFF."', '".SESSION_ADMIN."', '".SESSION_WINAPP."', '".SESSION_PDA."') AND `lastactivity` >= '".intval( $activitythreshold )."' ORDER BY `lastactivity` DESC;" );

		while ( $dbCore->nextRecord( ) )
		{
			if ( !isset( $staffidlist[$dbCore->Record["sessiontype"]][$dbCore->Record["typeid"]] ) )
			{
				$staffidlist[$dbCore->Record["sessiontype"]][$dbCore->Record["typeid"]] = 0;
			}
			$staffidlist[$dbCore->Record["sessiontype"]][$dbCore->Record["typeid"]]++;
			$onlinelist[$dbCore->Record["typeid"]]["fullname"] = $_SWIFT["staffcache"][$dbCore->Record["typeid"]]["fullname"];
			$onlinelist[$dbCore->Record["typeid"]]["staffid"] = $dbCore->Record["typeid"];
			$onlinelist[$dbCore->Record["typeid"]]["onlinecount"] = $staffidlist[$dbCore->Record["sessiontype"]][$dbCore->Record["typeid"]];
			$onlinelist[$dbCore->Record["typeid"]]["type"] = iif( $dbCore->Record["sessiontype"] == SESSION_WINAPP, "winapp", iif( $dbCore->Record["sessiontype"] == SESSION_ADMIN, "admin", iif( $dbCore->Record["sessiontype"] == SESSION_PDA, "pda", "staff" ) ) );
			$index++;
			$_staffidlist[] = $dbCore->Record["typeid"];
		}

		if ( !in_array( $_SWIFT["staff"]["staffid"], $_staffidlist ) )
		{
			$onlinelist[$index]["fullname"] = $_SWIFT["staff"]["fullname"];
			$onlinelist[$index]["staffid"] = $_SWIFT["staff"]["staffid"];
		}
		$template->assign( "onlineusers", $onlinelist );
	}

	function staffFooter( )
	{
		global $template, $dbCore;

		echo $template->displayTemplate( "staffcpfooter.tpl" );
	}

	function winappHeader( $title, $description, $selectedmenu )
	{
		global $_SWIFT, $template;

		$template->assign( "area", "winapp" );
		$template->assign( "sectiontitle", $title );
		$template->assign( "sectiondescription", $description );
		$template->assign( "title", $title." - ".sprintf( $_SWIFT["language"]["poweredby"], SWIFTPRODUCT ) );

		$template->assign( "menulinks", &$_SWIFT["winapplinks"][$selectedmenu] );

		echo $template->displayTemplate( "winappheader.tpl" );
	}

	function winappFooter( )
	{
		global $template;

		echo $template->displayTemplate( "winappfooter.tpl" );
	}

	function staffNavBar( $navpage, $navdescription = "", $selectednav = 0 )
	{
		global $_SWIFT, $template;

		$template->assign( "navpage", $navpage );
		$template->assign( "navdescription", $navdescription );
		$template->assign( "selectednav", $selectednav );
		$template->assign( "quicklinks", $this->quicklinks );
		$template->assign( "itemoptions", $this->itemoptions );

		$navicon = "bigicon_dashboard.gif";

		if ( $selectednav == "3" )
		{
			$navicon = "bigicon_livesupport.gif";
		}
		else if ( $selectednav == "4" )
		{
			$navicon = "bigicon_knowledgebase.gif";
		}
		else if ( $selectednav == "5" )
		{
			$navicon = "bigicon_downloads.gif";
		}
		else if ( $selectednav == "6" )
		{
			$navicon = "bigicon_troubleshooter.gif";
		}
		else if ( $selectednav == "7" )
		{
			$navicon = "bigicon_news.gif";
		}
		else if ( $selectednav == "9" )
		{
			$navicon = "bigicon_users.gif";
		}
		$template->assign( "navicon", $navicon );

		echo $template->displayTemplate( "staffnavbar.tpl" );
	}

	function assignQuickLink( $text, $link, $icon = "", $js = "" )
	{
		global $template;

		$template->assign( "isquicklinks", "true" );

		$linkcount = count( $this->quicklinks );
		$this->quicklinks[$linkcount]["link"] = $link;
		$this->quicklinks[$linkcount]["js"] = $js;
		$this->quicklinks[$linkcount]["text"] = $text;
		$this->quicklinks[$linkcount]["icon"] = $icon;

		return true;
	}

	function assignItemOption( $title, $link = "", $icon = "", $menuname = "", $customjs = "" )
	{
		global $template;

		$template->assign( "isitemoptions", "true" );

		$optcount = count( $this->itemoptions );
		$this->itemoptions[$optcount]["link"] = $link;
		$this->itemoptions[$optcount]["customjs"] = $customjs;
		$this->itemoptions[$optcount]["title"] = $title;
		$this->itemoptions[$optcount]["icon"] = $icon;
		$this->itemoptions[$optcount]["menuname"] = $menuname;

		return true;
	}

	function adminNavBar( $navpage, $navdescription = "", $selectednav = 0 )
	{
		global $_SWIFT, $template;

		$adminbar = $_SWIFT["adminbar"];
		for ( $ii = 0; $ii < count( $adminbar ); $ii++ )
		{
			if ( $selectednav == $ii )
			{
				$adminbar[$ii][4] = true;
			}
			$adminbar[$ii][3] = $_SWIFT["adminbaritems"][$ii];
		}

		$template->assign( "navpage", $navpage );
		$template->assign( "navdescription", $navdescription );
		$template->assign( "adminbar", $adminbar );
		$template->assign( "selectednav", $selectednav );
		$template->assign( "adminbaritems", &$_SWIFT["adminbaritems"] );

		echo $template->displayTemplate( "adminnavbar.tpl" );
	}
}

function iif( $expr, $rtrue = "", $rfalse = "" )
{
	return ($expr ? $rtrue:$rfalse);
}

function buildIN( $dataarray )
{
	$in = "";
	if ( !_is_array( $dataarray ) )
	{
		return "'0'";
	}
	foreach ( $dataarray as $key => $val )
	{
		$in .= "'".addslashes( $val )."',";
	}
	if ( trim( $in ) != "" )
	{
		return substr( $in, 0, -1 );
	}
	else
	{
		return "'0'";
        }
}

function swifthtmlspecialchars( $data )
{
	return htmlspecialchars( $data );
}

function registerShutdown( $type )
{
	global $_SWIFT;

	if ( !defined( "USESHUTDOWNFUNC" ) )
	{
		return false;
	}

	if ( $type == "settings" && $_SWIFT["shutdown"]["settings"] != 1 )
	{
		$_SWIFT["shutdown"]["settings"] = 1;
		register_shutdown_function( "rebuildSettings" );

		return true;
	}
	else if ( $type == "modules" && $_SWIFT["shutdown"]["modules"] != 1 )
	{
		$_SWIFT["shutdown"]["modules"] = 1;
		register_shutdown_function( "moduleDestructors" );

		return true;
	}
	else if ( $type == "query" && $_SWIFT["shutdown"]["query"] != 1 )
	{
		$_SWIFT["shutdown"]["query"] = 1;
		register_shutdown_function( "execShutdownQueries" );

		return true;
	}
	else if ( $type == "mail" && $_SWIFT["shutdown"]["mail"] != 1 )
	{
		$_SWIFT["shutdown"]["mail"] = 1;
		register_shutdown_function( "processMailQueue" );

		return true;
	}

	return false;
}

function rebuildSettings( )
{
	global $settings;
	$settings->rebuildArray( );
}

function moduleDestructors( )
{
	global $settings, $module, $_SWIFT;

	$registered = &$_SWIFT["registeredmodules"];
	if ( is_array( $registered ) )
	{
		reset( $registered );
		while ( list( $key, $val ) = each( $registered ) )
		{
			if ( $module->isLoaded( $key ) )
			{
				@call_user_func( array( $GLOBALS[$key], "_".$key ) );

			}
		}
	}
}

function execShutdownQueries( )
{
	global $_SWIFT, $dbCore;

	for ( $ii = 0; $ii < count( $_SWIFT["shutdownquery"] ); $ii++ )
	{
		$dbCore->query( $_SWIFT["shutdownquery"][$ii], 5 );
	}
}

function errorHandler( $errno, $errstr, $errfile, $errline )
{
	global $_SWIFT;

	switch ( $errno )
	{
		case SWIFT_FATAL :
			echo iif(SWIFT_AREA == SWIFT_CLI, 'SWIFT FATAL ERROR: ['. $errno .'] '.$errstr.' (File: '. $errfile .', Line: '. $errline .')'."\n", '<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><font color="red">SWIFT FATAL ERROR</font>:</b> [<b>'.$errno.'</b>] '.$errstr.' (File: '.$errfile.', Line: '.$errline.')</font><br />'."\r\n");
			$cntfatal = count( $_SWIFT["error"]["FATAL"] );
			$_SWIFT["error"]["FATAL"][$cntfatal]["number"] = $errno;
			$_SWIFT["error"]["FATAL"][$cntfatal]["string"] = $errstr;
			$_SWIFT["error"]["FATAL"][$cntfatal]["file"] = $errfile;
			$_SWIFT["error"]["FATAL"][$cntfatal]["line"] = $errline;
			break;

		case SWIFT_ERROR :
			echo iif(SWIFT_AREA == SWIFT_CLI, 'SWIFT ERROR: ['. $errno .'] '.$errstr.' (File: '. $errfile .', Line: '. $errline .')'."\n", '<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><font color="red">SWIFT ERROR</font>:</b> [<b>'.$errno.'</b>] '.$errstr.' (File: '.$errfile.', Line: '.$errline.')</font><br />'."\r\n");
			$cnterror = count( $_SWIFT["error"]["ERROR"] );
			$_SWIFT["error"]["ERROR"][$cnterror]["number"] = $errno;
			$_SWIFT["error"]["ERROR"][$cnterror]["string"] = $errstr;
			$_SWIFT["error"]["ERROR"][$cnterror]["file"] = $errfile;
			$_SWIFT["error"]["ERROR"][$cnterror]["line"] = $errline;
			break;

		case SWIFT_WARNING :
			echo iif(SWIFT_AREA == SWIFT_CLI, 'SWIFT WARNING: ['. $errno .'] '.$errstr.' (File: '. $errfile .', Line: '. $errline .')'."\n", '<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><font color="red">SWIFT WARNING</font>:</b> [<b>'.$errno.'</b>] '.$errstr.' (File: '.$errfile.', Line: '.$errline.')</font><br />'."\r\n");
			$cntwarning = count( $_SWIFT["error"]["WARNING"] );
			$_SWIFT["error"]["WARNING"][$cntwarning]["number"] = $errno;
			$_SWIFT["error"]["WARNING"][$cntwarning]["string"] = $errstr;
			$_SWIFT["error"]["WARNING"][$cntwarning]["file"] = $errfile;
			$_SWIFT["error"]["WARNING"][$cntwarning]["line"] = $errline;
			break;

		default:
			if ( !defined( "SWIFTDEBUG" ) )
			{
				return false;
			}

			$cntunknown = count( $_SWIFT["error"]["UNKNOWN"] );
			$_SWIFT["error"]["UNKNOWN"][$cntunknown]["number"] = $errno;
			$_SWIFT["error"]["UNKNOWN"][$cntunknown]["string"] = $errstr;
			$_SWIFT["error"]["UNKNOWN"][$cntunknown]["file"] = $errfile;
			$_SWIFT["error"]["UNKNOWN"][$cntunknown]["line"] = $errline;
			break;
	}
}

function buildHash( )
{
	srand( ( double )microtime * 1000000 );
	$id = md5( uniqid( rand( ) ) );
	return $id;
}

function buildRand( $min, $max )
{
	list( $usec, $sec ) = explode( ' ', microtime( ) );
	srand( ( float )$sec + ( float )$usec * 100000 );
	return rand( $min, $max );
}

function RGBtoHex( $R, $G, $B )
{
	return sprintf( "%02X%02X%02X", $R, $G, $B );
}

function ip2number( $dottedip )
{
	return sprintf( "%u", ip2long( $dottedip ) );
}

function number2ip( $ipnumber )
{
	return long2ip( $ipnumber );
}

function returnNone( $str )
{
	if ( trim( $str ) == "" )
	{
		return "";
	}
	else if ( empty( $str ) )
	{
		return "";
	}
	else
	{
		return $str;
        }
}

function hex2rgb( $hexcode )
{
	if ( trim( $hexcode ) == "" )
	{
		return;
	}

	$hexcode = str_replace( "#", "", $hexcode );

	$r = hexdec( substr( $hexcode, 0, 2 ) );
	$g = hexdec( substr( $hexcode, 2, 2 ) );
	$b = hexdec( substr( $hexcode, 4, 2 ) );
	$ret = array( );
	$ret["r"] = $r;
	$ret["g"] = $g;
	$ret["b"] = $b;
	return $ret;
}

function cleanVar( $var )
{
	return trim( preg_replace( "/[^a-zA-Z0-9\-\_]/", "", $var ) );
}

function buildURL( $url )
{
	global $settings, $_SWIFT;

	if ( $settings->store["security_sessionvar"] == "url" || $settings->store["security_sessionvar"] == "urlcookie" )
	{
		$sessionnovar = "?_s=".$_SWIFT["sessionid"];
		$sessionvar = "&_s=".$_SWIFT["sessionid"];
	}
	if ( strtolower( substr( $url, -4 ) ) == ".php" )
	{
		return $url.$sessionnovar;
	}
	else
	{
		return $url.$sessionvar;
        }
}

function loadFunctions( $functiontype )
{
	global $pdf;

	switch ( $functiontype )
	{
		case "pdf" :
			define( "FPDF_FONTPATH", "./includes/FPDF/font/" );
			require_once( "./includes/functions_pdf.php" );

			$pdf = new PDF;
			break;
	}

	return true;
}

function echoWinappData( $data, $doreturn = false )
{
	global $_SWIFT;

	if ( $_SWIFT["settings"]["cpu_compresswinappdata"] == 1 )
	{
		$compress = true;
	}
	else
	{
		$compress = false;
	}

	if ( $_REQUEST["utf"] == 1 && function_exists( "mb_convert_encoding" ) )
	{
		$data = mb_convert_encoding( $data, "UTF-8", "auto" );
	}

	if ( function_exists( "gzcompress" ) && $compress == true )
	{
		$undata = &$data;
		$sizeun = strlen( $undata );
		$md5un = md5( $undata );
		$gzdata = gzcompress( $undata, iif( isset( $_SWIFT["settings"]["cpu_winappcompresslevel"] ), $_SWIFT["settings"]["cpu_winappcompresslevel"], 9 ) );
		$sizegz = strlen( $gzdata );
		$md5gz = md5( $gzdata );

		$_data = "compressed;".$md5gz.";".$md5un.";".$sizegz.";".$sizeun.";".$gzdata;
		if ( $doreturn )
		{
			return $_data;
		}

		header( "Content-Length: ".strlen( $_data ) );

		echo $_data;

	}
	else
	{
		$undata = &$data;
		$sizeun = strlen( $undata );
		$md5un = md5( $undata );
		$gzdata = "";
		$sizegz = "0";
		$md5gz = "0";

		$_data = "uncompressed;".$md5gz.";".$md5un.";".$sizegz.";".$sizeun.";".$undata;
		if ( $doreturn )
		{
			return $_data;
		}

		header( "Content-Length: ".strlen( $_data ) );

		echo $_data;
	}
}

function headerNoCache( )
{
	header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
	header( "Last-Modified: ".gmdate( "D, d M Y H:i:s" )." GMT" );
	header( "Cache-Control: no-store, no-cache, must-revalidate" );
	header( "Cache-Control: post-check=0, pre-check=0", false );
	header( "Pragma: no-cache" );
}

function headerCache( )
{
	header( "Expires: ".gmdate( "D, d M Y H:i:s", time( ) + 3600*24 )." GMT" );
	header( "Cache-Control: max-age=3600, must-revalidate" );
}

function tpl_function_displayTemplate( $params, &$tpl )
{
	global $_SWIFT;

	return $tpl->displayTemplate( $params["name"] );
}

function tpl_function_urlencode( $params, &$tpl )
{
	global $_SWIFT;

	return urlencode( $params["value"] );
}

function tpl_function_includeURL( $params, &$tpl )
{
	global $_SWIFT;

	return implode( "", file( $params["url"] ) );
}

function isModuleRegistered( $params, $tpl = "" )
{
	global $_SWIFT;

	if ( $_SWIFT["registeredmodules"][$params] == "1" )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isValidEmail( $email )
{
	global $_SWIFT;

	if ( empty( $_SWIFT["settings"]["t_rvalemail"] ) && ( SWIFT_AREA == SWIFT_CLIENT || SWIFT_AREA == SWIFT_ADMIN || SWIFT_AREA == SWIFT_STAFF || SWIFT_AREA == SWIFT_API ) )
	{
		return true;
	}

	return eregi( "^[-!#$%&'*+\\./0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\\.)+([0-9A-Z]){2,5}$", trim( $email ) );
}

function edate( $format, $customtimeline = false )
{
	global $_SWIFT;

	$timeline = iif( !$customtimeline, DATENOW, $customtimeline );
	$timeline += $_SWIFT["timezone"] * 60 * 60;

	if ( $_SWIFT["daylightsavings"] == true && date( "I", $timeline ) == 1 )
	{
		$timeline += 60 * 60;
	}

	return date( $format, $timeline );
}

function getPart( $chunk )
{
	$j = explode( ".", $chunk );
	return $j[0];
}

function varDate( $diff )
{
	global $_SWIFT;

	$hour = getPart( floor( $diff / 3600 ) );
	$min = getPart( floor( $diff % 3600 / 60 ) );
	$s = getPart( $diff % 60 );
	if ( $hour > 0 )
	{
		if ( $hour >= 24 )
		{
			$days = floor( $hour / 24 );
			$actualhour = $hour - $days * 24;
			return sprintf( $_SWIFT["language"]["vardate1"], $days, $actualhour, $min, $s );
		}
                else
                {
		return sprintf( $_SWIFT["language"]["vardate2"], $hour, $min, $s );
                }
	}
	else if ( $min > 0 && $hour <= 0 )
	{
		return sprintf( $_SWIFT["language"]["vardate3"], $min, $s );
	}
        else
        {
	return sprintf( $_SWIFT["language"]["vardate4"], $s );
        }
}

function formattedSize( $size, $bytes = false )
{
	global $_SWIFT;

	if ( $size < 1024 && $bytes == true )
	{
		return number_format( $size, 2 )." ".$_SWIFT["language"]["bytes"];
	}
	else
	{
		$size1 = $size / 1024;
		if ( $size1 >= 1024 )
		{
			$size2 = $size1 / 1024;
			if ( $size2 >= 1024 )
			{
				$size3 = $size3 / 1024;

				return number_format( $size3, 2 )." ".$_SWIFT["language"]["gb"];
			}
			else
			{
				return number_format( $size2, 2 )." ".$_SWIFT["language"]["mb"];
			}
		}
		else
		{
			return number_format( $size1, 2 )." ".$_SWIFT["language"]["kb"];
		}
	}
}

function formattedDate( $timeline, $datetime = false )
{
	global $_SWIFT;

	if ( $datetime )
	{
		return edate( $_SWIFT["settings"]["dt_datetimeformat"], $timeline );
	}
	else
	{
		return edate( $_SWIFT["settings"]["dt_dateformat"], $timeline );
	}
}

function processMailQueue( )
{
	global $dbCore, $_SWIFT, $settings;

	chdir( $_SWIFT["cwd"] );

	$flushid = array( );
	require_once( "./includes/functions_mail.php" );

	if ( empty( $_SWIFT["settings"]["cpu_mailqueuebatch"] ) )
	{
		$batchcount = "5";
	}
	else
	{
		$batchcount = $_SWIFT["settings"]["cpu_mailqueuebatch"];
	}

	$dbCore->query( "SELECT * FROM `".TABLE_PREFIX."mailqueuedata` ORDER BY `mailqueuedataid` ASC LIMIT ".intval( $batchcount ).";" );
	while ( $dbCore->nextRecord( ) )
	{
		$mailObj = new SWIFT_Mail( );

		$flushid[] = $dbCore->Record["mailqueuedataid"];

		$mailObj->setSubject( $dbCore->Record["subject"] );

		if ( $dbCore->Record["ishtml"] == "1" )
		{
			$mailObj->setHtml( $dbCore->Record["datahtml"], $dbCore->Record["datatext"] );
		}
		else
		{
			$mailObj->setText( $dbCore->Record["datatext"] );
		}

		$mailObj->sendMail( $dbCore->Record["toemail"], $dbCore->Record["fromemail"], $dbCore->Record["fromname"], false );
	}

	if ( count( $flushid ) > 0 )
	{
		$dbCore->query( "DELETE FROM `".TABLE_PREFIX."mailqueuedata` WHERE `mailqueuedataid` IN (".buildIN( $flushid ).");" );
	}

	$result = $dbCore->queryFetch( "SELECT COUNT(*) AS totalitems FROM `".TABLE_PREFIX."mailqueuedata`;" );
	$settings->updateKey( "mail", "queuecount", $result["totalitems"], true );
}

function _is_array( $extarray )
{
	if ( !is_array( $extarray ) || !count( $extarray ) )
	{
		return false;
	}
        else
        {
	return true;
        }
}

function getProcessedHTML( $contents )
{
	$contentsproc = strtoupper( $contents );

	if ( stristr( $contentsproc, "<DIV>" ) || stristr( $contentsproc, "<BR>" ) || stristr( $contentsproc, "<BR />" ) || stristr( $contentsproc, "<BR>" ) || stristr( $contentsproc, "<P>" ) )
	{
		return autoLink( $contents );
	}
	else
	{
		return autoLink( nl2br( $contents ) );
	}
}

function stri_replace( $find, $replace, $string )
{
	if ( !is_array( $find ) )
	{
		$find = array( $find );
	}
	if ( !is_array( $replace ) )
	{
		if ( !is_array( $find ) )
		{
			$replace = array( $replace );
		}
		else
		{
			$c = count( $find );
			$rString = $replace;
			unset( $replace );
			for ( $i = 0; $i < $c; $i++ )
			{
				$replace[$i] = $rString;
			}
		}
	}

	foreach ( $find as $fKey => $fItem )
	{
		$between = explode( strtolower( $fItem ), strtolower( $string ) );
		$pos = 0;
		foreach ( $between as $bKey => $bItem )
		{
			$between[$bKey] = substr( $string, $pos, strlen( $bItem ) );
			$pos += strlen( $bItem ) + strlen( $fItem );
		}
		$string = implode( $replace[$fKey], $between );
	}
	return $string;
}

function getProcessedText( $contents, $ishtml = false )
{
	global $_SWIFT;

	$replacement = array( '<DIV>', '<BR>', '<BR />', '</P>' );
	$replacementto = array( '<DIV>'.SWIFT_CRLF, '<BR>'.SWIFT_CRLF, '<BR />'.SWIFT_CRLF, '</P>'.SWIFT_CRLF );

	if ( $_SWIFT["settings"]["cpu_enablehtmlmails"] == 1 || $ishtml == true )
	{
		return strip_tags( stri_replace( $replacement, $replacementto, $contents ) );
	}
        else
        {
		return $contents;
        }
}

function fetchmicrotime( )
{
	list( $usec, $sec ) = explode( " ", microtime( ) );
	return ( float ) ( ( float )$usec + ( float )$sec );
}

function getFileExtension( $filename )
{
	$filedata = explode( ".", $filename );
	return strtolower( $filedata[count( $filedata ) - 1] );
}

function loadStaffCaches( )
{
	global $datastore;

	$datastore->cache( "staffcache" );
	$datastore->cache( "staffgroupcache" );
	$datastore->cache( "groupsettingcache" );
	$datastore->cache( "staffassigncache" );
	$datastore->cache( "groupassigncache" );
	$datastore->cache( "departmentcache" );
}

function autoLink( $text )
{
	$ret = ' '.$text;
	$ret = preg_replace( "#([\t\r\n ])([a-z0-9]+?){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="\2://\3" target="_blank">\2://\3</a>', $ret );
	$ret = preg_replace( "#([\t\r\n ])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="http://\2.\3" target="_blank">\2.\3</a>', $ret );
	$ret = preg_replace( "#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret );

	$ret = substr( $ret, 1 );

	return $ret;
}

function md5_array( $array )
{
	return md5( serialize( $array ) );
}

function getAssignedDepartments( $module = false, $staffid = false )
{
	global $_SWIFT;

	if ( empty( $module ) )
	{
		$module = MODULE_TICKETS;
	}

	if ( !$staffid )
	{
		$_staffid = $_SWIFT["staff"]["staffid"];
	}
	else
	{
		$_staffid = $staffid;
	}

	if ( isset( $_SWIFT["assigncache"] ) )
	{
		return $_SWIFT["assigncache"];
	}

	$_staff = $_SWIFT["staffcache"][$_staffid];
	if ( empty( $_staff["staffid"] ) )
	{
		return false;
	}
	$_staffgroupid = $_staff["staffgroupid"];

	$departmentidlist = array( );

	if ( $_staff["groupassigns"] == 1 && _is_array ( $_SWIFT["groupassigncache"][$_staffgroupid] ) )
	{
		foreach ( $_SWIFT["groupassigncache"][$_staffgroupid] as $key => $val )
		{
			if ( !in_array( $val, $departmentidlist ) ) {
                            $departmentidlist[] = $val;
                        }
		}
	}
	else
	{
		if ( !_is_array( $_SWIFT["staffassigncache"][$_staffid] ) )
		{
			return false;
		}
		foreach ( $_SWIFT["staffassigncache"][$_staffid] as $key => $val )
		{
			if ( !in_array( $val, $departmentidlist ) )
			{
				$departmentidlist[] = $val;
			}
		}
	}

	$_departmentidlist = array( );
	foreach ( $departmentidlist as $key => $val )
	{
		if ( $_SWIFT["departmentcache"][$val]["departmentmodule"] == $module )
		{
			$_departmentidlist[] = $val;
		}
	}

	$_SWIFT["assigncache"] = $_departmentidlist;

	return $_departmentidlist;
}

function getCalendarDateline( $date )
{
	global $_SWIFT;

	$datearray = explode( "/", $date );
	if ( count( $datearray ) != 3 )
	{
		return "0";
	}
	else if ( $_SWIFT["settings"]["dt_caltype"] == "us" )
	{
		$dateline = mktime( 0, 0, 0, intval( $datearray[0] ), intval( $datearray[1] ), intval( $datearray[2] ) );

                return $dateline;
	}
	else
	{
		$dateline = mktime( 0, 0, 0, intval( $datearray[1] ), intval( $datearray[0] ), intval( $datearray[2] ) );

		return $dateline;
	}
}

function generateCalendarTimeline( $date )
{
	global $_SWIFT;

	if ( $_SWIFT["settings"]["dt_caltype"] == "us" )
	{
		$timeline = date( "m/d/Y", $date );

                return $timeline;
	}

	$timeline = date( "d/m/Y", $date );

	return $timeline;
}

function tpl_function_processCPMenu( $params, &$tpl )
{
	global $_SWIFT;

	if ( $_SWIFT["settings"]["g_jscache"] == 1 )
	{
		$processenable = false;
	}
	else
	{
		$processenable = true;
	}

	$dowrite = false;

	if ( $_SWIFT["settings"]["g_cpmenu"] == "hover" )
	{
		$tpl->assign( "cpmenu", "hover" );
	}
	else
	{
		$tpl->assign( "cpmenu", "click" );
	}

	$replacements = array( '%PRV%', '%COMMENTKB%', '%COMMENTTR%', '%COMMENTDL%', '%COMMENTNW%' );
	if ( !empty( $_SWIFT["staff"]["pmunread"] ) )
	{
		$pmunread = " (".$_SWIFT["staff"]["pmunread"].")";
	}
	$replacewith = array(
	$pmunread,
	iif( !empty( $_SWIFT["commentcache"][COMMENT_KNOWLEDGEBASE] ), " (".$_SWIFT["commentcache"][COMMENT_KNOWLEDGEBASE].")" ),
	iif( !empty( $_SWIFT["commentcache"][COMMENT_TROUBLESHOOTER] ), " (".$_SWIFT["commentcache"][COMMENT_TROUBLESHOOTER].")" ),
	iif( !empty( $_SWIFT["commentcache"][COMMENT_DOWNLOADS] ), " (".$_SWIFT["commentcache"][COMMENT_DOWNLOADS].")" ),
	iif( !empty( $_SWIFT["commentcache"][COMMENT_NEWS] ), " (".$_SWIFT["commentcache"][COMMENT_NEWS].")" ),
	);

	if ( $processenable == false )
	{
		$datahash = $params["area"]."cpmenu".$_SWIFT["settings"]["g_cpmenu"];
		$filepath = "./cache/".$datahash.".js";
		if ( !file_exists( $filepath ) )
		{
			$jscachedata = $tpl->displayTemplate( "cpmenu.tpl" );
			$jscachedata = str_replace( $replacements, $replacewith, $jscachedata );
			$fp = fopen( $filepath, "w+" );
			fwrite( $fp, $jscachedata );
			fclose( $fp );
			@chmod( $filepath, 0666 );
		}

		$returnvar = '<script type="text/javascript" src="'.$_SWIFT["swiftpath"].'cache/'.$datahash.'.js"></script>';
	}
	else
	{
		$returnvar = '<script language="Javascript">'.SWIFT_CRLF;
		$returnvar .= $tpl->displayTemplate( "cpmenu.tpl" );
		$returnvar .= '</script>';
	}

	$returnvar = str_replace( $replacements, $replacewith, $returnvar );

	return $returnvar;
}

function tpl_function_processCPAdminNavBar( $params, &$tpl )
{
	global $_SWIFT;

	if ( $_SWIFT["settings"]["g_jscache"] == 1 )
	{
		$processenable = true;
	}
	else
	{
		$processenable = false;
	}

	$dowrite = false;

	if ( $processenable == true )
	{
		$datahash = "cpadminnavbar";
		$filepath = "./cache/".$datahash.".js";
		if ( !file_exists( $filepath ) )
		{
			$jscachedata = JSCacheToString( $tpl->displayTemplate( "adminnavbardata.tpl" ) );
			$fp = fopen( $filepath, "w+" );
			fwrite( $fp, $jscachedata );
			fclose( $fp );
			@chmod( $filepath, 0666 );
		}
		$returnvar = '<script type="text/javascript" src="'.$_SWIFT["swiftpath"].'cache/'.$datahash.'.js"></script>';

	}
	else
	{
		$returnvar = '<script language="Javascript">'.SWIFT_CRLF;
		$returnvar .= JSCacheToString( $tpl->displayTemplate( "adminnavbardata.tpl" ) );
		$returnvar .= '</script>';
	}

	return $returnvar;
}

function JSCacheToString( $data )
{
	$data = preg_replace( "#(\r\n|\r|\n)#s", SWIFT_CRLF, $data );
	return "document.write('".str_replace( SWIFT_CRLF, "\\n", addslashes( $data ) )."');".SWIFT_CRLF;
}

function strColorDate( $diff, $flipcolors = false, $nocolors = false )
{
	global $_SWIFT;

	if ( $flipcolors == true && $nocolors == false )
	{
		$colorsec = "tickettextred";
		$colormin = "tickettextorange";
		$colorhr = "tickettextblue";
		$colordays = "tickettextgreen";
	}
	else if ( $flipcolors == false && $nocolors == false )
	{
		$colorsec = "tickettextgreen";
		$colormin = "tickettextblue";
		$colorhr = "tickettextorange";
		$colordays = "tickettextred";
	}

	$hour = getPart(floor($diff/3600));
	$min = getPart(floor(($diff%3600)/60));
	$s = getPart($diff%60);
	if ($hour > 0) {
		if ($hour >= 24) {
			$days = floor($hour/24);
			$actualhour = $hour-($days*24);
			return '<span class=\''. $colordays .'\'>'.sprintf($_SWIFT["language"]["vardate1"], $days, $actualhour, $min, $s).'</span>';
		}
                else
                {
			return '<span class=\''. $colorhr .'\'>'.sprintf($_SWIFT["language"]["vardate2"], $hour, $min, $s).'</span>';
		}
	}
        else if ($min > 0 && $hour <= 0)
        {
		return '<span class=\''. $colormin .'\'>'.sprintf($_SWIFT["language"]["vardate3"], $min, $s).'</span>';
	}
	else
	{
		return '<span class=\''. $colorsec .'\'>'.sprintf($_SWIFT["language"]["vardate4"], $s).'</span>';
	}
}

function stripTrailingSlash( $url )
{
	if ( substr( $url, -1, 1 ) == "/" )
	{
		return substr( $url, 0, strlen( $url ) - 1 );
	}

	return $url;
}

function processWidgets( $widgets )
{
	global $module;

	$newwidgets = array( );
	$index = 0;

	foreach ( $widgets as $key => $val )
	{
		$newwidgets[$index] = $val;
		$newwidgets[$index]["split"] = $index%2;

		if ( ( $index+1 ) == count( $widgets ) )
		{
			$newwidgets[$index]["split"] = 1;
		}
		$index++;
	}

	return $newwidgets;
}

?>